import {ref, watch} from "vue";
import {getProjectDetail, getSubmissions} from "@/api/projects.js";
import {useRoute} from "vue-router";
import {getStudentUsers} from "@/api/user.js";
export function useAssignmentReview() {
    const route = useRoute();
    const project = ref({})
    const submissions = ref([])
    const userOptions = ref([]);
    const loading = ref(true);
    const error = ref(null);
    const updateProject = async (id) => {
        try {
            const projResp = await getProjectDetail(id)
            const assignment = projResp.assignment || {}
            const leader = assignment.teamMembers?.find(it => it.teamRole === 'TEAM_LEAD')?.userId || null
            const members = assignment.teamMembers?.filter(it => it.teamRole === 'TEAM_MEMBER').map(it => it.userId) || []
            
            // Structure the data to match what the component expects
            project.value = {
                ...projResp,
                leader: leader,
                members: members,
            }
            console.log('project', project.value)
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }

    const updateSubmissions = async (id) => {
        try {
            const resp = await getSubmissions(id)
            submissions.value = resp
            console.log('submission', submissions.value)
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }

    const loadUsers = async () => {
        try {
            loading.value = true;
            error.value = null;
            const resp = await getStudentUsers();
            userOptions.value = resp.students.map(it => ({
                label: it.realName,
                value: it.id
            }));
        } catch (err) {
            error.value = err;
            console.error('Failed to load users:', err);
        } finally {
            loading.value = false;
        }
    };

    const refreshData = async () => {
        try {
            await updateProject(route.params.id)
            await updateSubmissions(route.params.id)
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }



    watch(() => route.params.id, async (newId) => {
        if (!newId) {
            return;
        }
        try {
            await updateProject(newId)
            await updateSubmissions(newId)
            await loadUsers()
        } catch (error) {
            console.error('Failed to load project details:', error)
        }
    }, {immediate: true})

    return {
        project,
        submissions,
        userOptions,
        refreshData
    }
}